const express = require("express")    //加载express
const app = express();                //调用exprss()获取 express()函数时express模块导出的顶级函数
const path = require("path");

//处理body请求体的中间件
app.use(express.urlencoded())
app.use(express.json())

//cors跨域
//设置请求对应的处理函数 当客户端以GET方法请求时就会调用函数
// app.get("userInfo", (req, res) => {     //req = request或者require请求   res = response 响应
  //允许所有的请求都能跨域
//   res.set("Access-Control-Allow-origin", "*")

// })


//查询学生信息接口
app.get("/user", (req, res) => {
  const token = req.headers.token;
  console.log(token, "token");
  if (!token) {
    return res.send({
      code: 10002,
      msg: "没有权限",
      data: null
    })
  }
  const {
    userId
  } = req.query;


  //如果查询失败
  if (userId !== "001") {
    return res.send({
      code: 10001,
      msg: "查询失败",
      data: null
    })
  }


  //查询成功 响应
  res.send({
    code: 10000,
    msg: "查询成功",
    data: {
      name: "李博",
      age: 18,
      sex: "男"
    }
  })

})

//定义一个延时响应的请求接
app.get("./userLazy", (req, res) => {
  setTimeout(() => {
    const token = req.headers.token;
    console.log("token", token);
    if(!token) {
      return res.send({
        code: 10002,
        msg: "没有权限",
        data: null
      })
    }  

    const {
      userId
    } = res.query;

    //如果查询失败
    if (userId !== "001") {
      return res.send ({
        code: 10001,
        msg: "查询失败",
        data: null
      })
    }


    //查询成功，响应
    res.send({
      code: 10000,  
      msg: "查询成功",
      data: {
        name: "李博",
        age: 18,
        sex: "男"
      }
    })    
  }, 3000)
})


app.post("/adduser", (req, res) => {
  console.log("adduser");
  console.log(req.body, "req.body");
  console.log(req.query, "req.query");
  const {
    name,
    age,
    sex
  } = req.body;

  if (!name || !age || !sex) {
    return res.send({
      code: 10001,
      mes: "添加失败",
      data: null
    })
  }

  res.send({
    code: 10000,
    mes: "添加成功",
    data: null
  })
})


app.put("/updateuser", (req, res) => {
  const {
    userId,
    age,
    sex
  } = req.body;

  console.log(userId, age, sex, "更新");

  res.send({
    code: 10000,
    mes: "更新成功",
    data: null
  })
})

app.delete("/deleteuser", (req, res) => {
  const {
    userId
  } = req.query;
  console.log(userId, "删除");

  res.send({
    code: 10000,
    mes: "删除成功",
    data: null
  })
})

//静态资源部署接口
app.get("./1", (req, res) => {
  const filePath = path.resolve(__dirname, "./axios基础使用.html");
  res.sendFile(filePath);
})


app.listen(5500, () => {
  console.log("服务器请求成功 请访问http://127.0.0.1:5500");
})